import base64
import jwt
from fastapi import Request
import aioredis
# 配置 Redis 连接
import asyncio
import redis
from configs.auth_config import *
import json
from typing import List
from api_server.utils import BaseResponse
import pydantic
from pydantic import BaseModel, BaseSettings
from typing import (
    TYPE_CHECKING,
    Literal,
    Optional,
    Callable,
    Generator,
    Dict,
    Any,
    Awaitable,
    Union,
    Tuple
)
from datetime import datetime
from configs import logger


# 定义全局配置类
class Settings(BaseSettings):
    datetime_format: str = '%Y-%m-%d %H:%M:%S'


settings = Settings()


class LoginUser(BaseModel):
    '''
                    {
                "@type": "com.etone.platform.common.core.domain.model.LoginUser",
                "account": "admin",
                "browser": "Chrome 12",
                "deptId": 103,
                "expireTime": 1716280689108,
                "ipaddr": "192.168.11.18",
                "loginLocation": "内网IP",
                "loginTime": 1716278889108,
                "nickName": "admin",
                "os": "Windows 10",
                "token": "2b3a6c02-7b05-475b-a231-d4ab33030b56",
                "user": {
                "admin": true,
                    "avatar": "/profile/avatar/2024/05/09/blob_20240509203651A003.jpeg",
                    "createBy": "admin",
                    "createTime": "2022-09-21 21:11:01",
                    "delFlag": "0",
                    "dept": {
                "ancestors": "0,100,101",
                        "children": [],
                        "deptId": 103,
                        "deptName": "研发部门",
                        "leader": "若依",
                        "orderNum": 1,
                        "params": {
                "@type": "java.util.HashMap"
                        },
                        "parentId": 101,
                        "status": "0"
                    },
                    "deptId": 103,
                    "email": "ry@163.com",
                    "loginDate": "2024-05-21 10:17:35",
                    "loginIp": "192.168.223.247",
                    "nickName": "移动员工1",
                    "params": {
                "@type": "java.util.HashMap"
                    },
                    "password": "$2a$10$29IedUDCDvLlW.4YQNlvCuMHinlnxj.86IqQr2snOkvokJdkS9zGm",
                    "phonenumber": "15888888888",
                    "remark": "管理员",
                    "roles": [
                        {
                "admin": true,
                            "dataScope": "1",
                            "deptCheckStrictly": false,
                            "flag": false,
                            "menuCheckStrictly": false,
                            "params": {
                "@type": "java.util.HashMap"
                            },
                            "roleId": 1,
                            "roleKey": "admin",
                            "roleName": "超级管理员",
                            "roleSort": "1",
                            "status": "0"
                        }
                    ],
                    "sex": "0",
                    "status": "0",
                    "userId": 1,
                    "userName": "admin"
                },
                "userId": 1,
                "username": "admin"
            }
    '''
    user_id: int = pydantic.Field(1, description='用户id')
    user_name: str = pydantic.Field('sample', description='用户名称')
    is_admin: bool = pydantic.Field(False, description='是否是管理员')

    class Config:
        json_encoders = {
            datetime: lambda v: v.strftime(settings.datetime_format)
        }


def get_user_info(request: Request):
    '''
    获取用户信息
    '''
    try:
        uuid = request.state.uuid
    except:
        uuid = None
    try:
        return auth_jwt.get_user_info_by_uid(uuid)
    except:
        return None


def string_to_base64(input_string: str) -> str:
    # 将字符串转换为字节
    string_bytes = input_string.encode('utf-8')
    # 将字节编码为Base64
    base64_bytes = base64.b64encode(string_bytes)
    # 将Base64字节转换为字符串
    base64_string = base64_bytes.decode('utf-8')
    return base64_string


class JwtUti:

    def __init__(self):
        '''
        jwt处理
        '''

    def get_user_info(self, token):
        try:
            red = RedisUtil()
            user_info = red.get(self.get_uuid(token))
            if user_info is None:
                return None
            pattern = r'Set\["[^:"]+:[^:"]+:[^:"]+"\]'
            user_info = re.sub(pattern, '""', user_info)
            data = json.loads(user_info)
            login_user = LoginUser(user_id=data['userId'], user_name=data['username'], is_admin=data['user']['admin'])
            return login_user
        except Exception as e:
            logger.exception(e)
        return None

    def get_user_info_by_uid(self, uid):
        try:
            red = RedisUtil()
            user_info = red.get(uid)
            if user_info is None:
                return None
            pattern = r'Set\["[^:"]+:[^:"]+:[^:"]+"\]'
            user_info = re.sub(pattern, '""', user_info)
            data = json.loads(user_info)
            login_user = LoginUser(user_id=data['userId'], user_name=data['username'], is_admin=data['user']['admin'])
            return login_user
        except Exception as e:
            logger.exception(e)
        return None

    def get_uuid(self, token):
        if token is None:
            return None
        try:
            token = token.replace('Bearer', '').replace('bearer', '')
            key = string_to_base64(SECRET_KEY)
            payload = jwt.decode(token, key, algorithms=[ALGORITHM], options={"verify_signature": False})
            return payload['login_user_key']
        except Exception as e:
            return None


class RedisUtil:
    def __init__(self):
        '''
        redis处理
        '''
        self.redis_client = redis.StrictRedis(
            host=REDIS_HOST,
            port=REDIS_PORT,
            password=REDIS_PASSWORD,
            decode_responses=True
        )

    def get(self, uuid):
        if uuid is None:
            return None
        try:
            key = '%s:%s' % ("login_tokens", uuid)
            return self.redis_client.get(key)
        except:
            return None


auth_jwt = JwtUti()
import re


def init_sys_kb():
    from api_server.knowledge_base.kb_api import list_kbs, create_kb, delete_kb
    '''
    初始化默认的知识库
    '''
    # create_kb(request=None,knowledge_base_name='sjgzzdzsk',
    #           kb_nickname="审计规章制度知识库",
    #           vector_store_type='pg',
    #           embed_model='bge-large-zh-v1.5',
    #           kb_type='public')

    create_kb(request=None,knowledge_base_name='sjzgqrzsk',
              kb_nickname="整改跟进审计确认",
              vector_store_type='pg',
              embed_model='bge-large-zh-v1.5',
              kb_type='public')


if __name__ == "__main__":
    init_sys_kb()
    # temp = '{"@type":"com.etone.platform.common.core.domain.model.LoginUser","account":"admin","browser":"Chrome 12","deptId":103,"expireTime":1716280689108,"ipaddr":"192.168.11.18","loginLocation":"内网IP","loginTime":1716278889108,"nickName":"admin","os":"Windows 10","permissions":Set["*:*:*"],"token":"2b3a6c02-7b05-475b-a231-d4ab33030b56","user":{"admin":true,"avatar":"/profile/avatar/2024/05/09/blob_20240509203651A003.jpeg","createBy":"admin","createTime":"2022-09-21 21:11:01","delFlag":"0","dept":{"ancestors":"0,100,101","children":[],"deptId":103,"deptName":"研发部门","leader":"若依","orderNum":1,"params":{"@type":"java.util.HashMap"},"parentId":101,"status":"0"},"deptId":103,"email":"ry@163.com","loginDate":"2024-05-21 10:17:35","loginIp":"192.168.223.247","nickName":"移动员工1","params":{"@type":"java.util.HashMap"},"password":"$2a$10$29IedUDCDvLlW.4YQNlvCuMHinlnxj.86IqQr2snOkvokJdkS9zGm","phonenumber":"15888888888","remark":"管理员","roles":[{"admin":true,"dataScope":"1","deptCheckStrictly":false,"flag":false,"menuCheckStrictly":false,"params":{"@type":"java.util.HashMap"},"roleId":1,"roleKey":"admin","roleName":"超级管理员","roleSort":"1","status":"0"}],"sex":"0","status":"0","userId":1,"userName":"admin"},"userId":1,"username":"admin"}'
    # # Set["*:*:*"]
    # pattern = r'Set\["[^:"]+:[^:"]+:[^:"]+"\]'
    # temp = re.sub(pattern, '""', temp)
    # print(json.loads(temp))
